<template>
  <a-modal
    width="100%"
    :visible='editVisible'
    :confirm-loading='loading'
    :title="isUpdate ? '修改' : '新建'"
    :body-style="{ paddingBottom: '8px' }"
    :style="{ top: '0px' }"
    @update:visible='updateEditVisible'
    :footer="null"
  >
    <div class='ele-body ele-body-card'>
      <!-- 顶部卡片 -->
      <a-card
        :bordered='true'
        :body-style="{padding: '20px'}">
        <a-form
          ref='form'
          :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
          :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
          @submit='checkAndPushSubmitConfig'
        >
          <a-divider orientation="left">围栏配置</a-divider>
          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label='围栏名字:' name='checkInterval'>
                <a-input v-model:value='vehicleGeoForm.geofenceName' style="width: 180px" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24' />
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label='GEO ID:' name='geoId'>
                <a-select
                  show-search
                  v-model:value="form.geoId"
                  placeholder="请选择围栏id"
                  style="width: 205px;"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="null"
                  @change="handleChange"
                >
                  <a-select-option v-for="item in geoIds" :key="item.id" >
                    {{ item.id }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'>
            </a-col>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label="Model:" name="geoMode">
                <a-select v-model:value="form.geoMode">
                  <a-select-option :value="0">Disable</a-select-option>
                  <a-select-option :value="1">Entering the zone</a-select-option>
                  <a-select-option :value="2">Exiting the zone</a-select-option>
                  <a-select-option :value="3">Both entering and exiting</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'>
            </a-col>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label='百度坐标系纬度:' name='bdLatitude'>
                <a-input-number
                  :step="0.000001"
                  string-mode
                  :min="0" v-model:value='form.bdLatitude' style="width: 180px" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'>
            </a-col>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label='百度坐标系经度:' name='bdLongitude'>
                <a-input-number
                  :step="0.000001"
                  string-mode
                  :min="0" v-model:value='form.bdLongitude' style="width: 180px" allow-clear />
                <a-button style="margin-left: 25px;" type='primary' html-type='button' @click='selectMapAction'>地图选择位置</a-button>
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'>
            </a-col>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label='半径大小(m):' name='radius'>
                <a-input-number :min="50" :max="6000000" v-model:value='form.radius' style="width: 180px" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'>
            </a-col>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label='检查周期(秒):' name='checkInterval'>
                <a-input-number :min="0" :max="600000" v-model:value='form.checkInterval' style="width: 180px" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24' />
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label='StartTime(HHMM):' name='startTime'>
                <a-input v-model:value='form.startTime' placeholder='请输入检测开始时间' allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'>
            </a-col>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label='EndTime(HHMM):' name='endTime'>
                <a-input v-model:value='form.endTime' placeholder='请输入检测结束时间' allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'>
            </a-col>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='14' :sm='24' :xs='24'>
              <a-form-item label="State Model:" name="stateMode">
                <a-select v-model:value="form.stateMode">
                  <a-select-option :value="0">Report upon getting the state for the first time</a-select-option>
                  <a-select-option :value="1">not report uniting state changes</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md='10' :sm='24' :xs='24'>
            </a-col>
          </a-row>

          <a-row :gutter='8'>
            <a-col :md='2' :sm='24' :xs='24'>
            </a-col>
            <a-col :md='8' :sm='24' :xs='24'>
              <a-button type='primary' html-type='submit' :loading='formSubmitLoading'>
                提交
              </a-button>
              <a-button style="margin-left: 25px;" type='primary' html-type='button' @click='readGEO' :loading='readLoading'>
                读取
              </a-button>
            </a-col>
            <a-col :md='8' :sm='24' :xs='24'>
            </a-col>
            <a-col :md='6' :sm='24' :xs='24'></a-col>
          </a-row>
        </a-form>
      </a-card>
      <vehicle-manager-geofence-list-circle-manager-bmap  v-if="showSelectPoint" v-model:visible="showSelectPoint" :point="currentPoint" @done="fillPoint" />
    </div>
  </a-modal>
</template>

<script>

import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';
import { message } from 'ant-design-vue';
import {VehicleConfigCircleGeofenceApi} from "@/api/property/vechile/VehicleConfigCircleGeofenceApi";
import VehicleManagerGeofenceListCircleManagerBmap from './circle-geofence-bmap.vue'
import {VehicleGeofenceCircleClientApi} from "@/api/property/vechile/VehicleGeofenceCircleClientApi";



export default {
  name: 'VehicleManagerGeofenceCircleManagerEdit',
  components: {
    VehicleManagerGeofenceListCircleManagerBmap
  },
  emits: ['done', 'update:editVisible'],
  props: {
    // 弹窗是否打开
    editVisible: Boolean,
    // 修改回显的数据
    data: Object,
    vehicleData : Object
  },
  mounted() {
    let that = this;
    if (this.data) {
      this.vehicleGeoForm = Object.assign({}, this.data);
      that.geoIds = [
        {
          'id' : this.data.geoId,
          'name': this.data.geoId,
        }
      ];
      that.getGeoConfigDetail(this.data.geoId);
      this.isUpdate = true;
    } else {
      this.form = {};
      this.vehicleGeoForm = {};
      this.isUpdate = false;
      if (this.vehicleData != null) {
        let clientListPromse = VehicleGeofenceCircleClientApi.list({"vehicleId" : this.vehicleData.vehicleId, "recordId" : this.vehicleData.recordId})
        clientListPromse.then(function(list){
          let readyGeoIds = [];
          for(let i = 0;i < list.length; i++) {
            readyGeoIds.push(list[i].geoId);
          }
          let geoIds = [];
          let currentGeoId = null;
          for(let i = 0;i < 20; i++) {
            if (readyGeoIds.indexOf(i) === -1) {
              geoIds.push({
                'id' : i,
                'name': i,
              });
              if (currentGeoId === null) {
                currentGeoId = i;
              }
            }
          }
          if (geoIds.length == 0) {
            message.error("最多只允许20个围栏");
          } else {
            that.geoIds = geoIds;
            that.getGeoConfigDetail(currentGeoId);
          }
        });
      }
    }
    if (this.$refs.form) {
      this.$refs.form.clearValidate();
    }
  },
  data() {
    return {
      form : {},
      vehicleGeoForm : {},
      currentConfig : {},
      currentPoint : {},
      loading : false,
      geoIds : [],

      formSubmitLoading : false,
      formSubmitTimer : undefined,

      readLoading : false,
      readTimer : undefined,
      showSelectPoint : false,
      // 是否是修改
      isUpdate: false,
    };
  },
  methods: {
    fillPoint(point) {
      if (point.latitude > 0 && point.longitude > 0) {
        this.form.bdLatitude = point.latitude.toFixed(6);
        this.form.bdLongitude = point.longitude.toFixed(6);
        this.form.latitude = 0;
        this.form.longitude = 0;
        this.form.gcjLatitude = 0;
        this.form.gcjLongitude = 0;
      }
    },
    selectMapAction () {
      this.currentPoint = {
        latitude : this.form.bdLatitude,
        longitude : this.form.bdLongitude
      };
      this.showSelectPoint = true;
    },
    handleChange (value) {
      if (!this.isUpdate) {
        this.getGeoConfigDetail(value);
      }
    },
    getGeoConfigDetail(geoId) {
      let that = this;
      let params = {
        "recordId" : this.vehicleData.recordId,
        "geoId" : geoId || 0
      };
      VehicleConfigCircleGeofenceApi.list(params).then(result => {
        if (result && result.length == 1) {
          that.form = result[0] || {"geoId" : params.geoId};
        } else {
          that.form = {"geoId" : params.geoId};
        }
        that.currentConfig = JSON.parse(JSON.stringify(that.form));
      });
    },

    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.vehicleData.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail2(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },


    //-------提交
    clearSubmitConfig(){
      this.formSubmitLoading = false;
      clearInterval(this.formSubmitTimer);
    },

    checkSubmitConfig(){
      let that = this;
      this.checkProcess(5, this.clearSubmitConfig, function(){
        // 关闭弹框，通过控制visible的值，传递给父组件
        that.updateEditVisible(false);
        // 触发父组件done事件
        that.$emit('done');
      });
    },

    checkAndPushSubmitConfig() {
      let workerDetailparams = {
        recordId: this.vehicleData.recordId,
        sceneDictate: 5
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitConfigSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitConfigSubmit() {
      if (this.form.geoMode == 0 && (this.form.latitude > 0 || this.form.longitude > 0)) {
        message.error('mode是禁止的，设置无效');
        return;
      }
      this.loading = true;
      let that = this;
      let vehicleGeoFormResult = null;
      if (this.isUpdate) {
        vehicleGeoFormResult = VehicleGeofenceCircleClientApi.edit(this.vehicleGeoForm);
      } else {
        let addParams = {
          "geofenceName" : this.vehicleGeoForm.geofenceName,
          "vehicleId" : this.vehicleData.vehicleId,
          "recordId" :  this.vehicleData.recordId,
          "geoId" : this.form.geoId
        };
        vehicleGeoFormResult = VehicleGeofenceCircleClientApi.add(addParams);
      }
      vehicleGeoFormResult
        .then(result => {
          let updateDataRecord = {
            recordId: that.vehicleData.recordId,
            templateCode: 'vehicle',
            updateData: JSON.stringify({ old: that.currentConfig, update: that.form}),
            dictate : 5, //AT+GTGEO=
            sceneDictate : 5 //GTGEO
          };
          let result1 = DeviceCommandDownQueueApi.add(updateDataRecord);
          result1
            .then(result2 => {
              that.loading = false;
              message.success(result2.message);

              that.formSubmitLoading = true; //转圈
              that.formSubmitTimer = setInterval(that.checkSubmitConfig, 5000);
            })
            .catch(() => {
              that.loading = false;
            });

        })
        .catch(() => {
          that.loading = false;
        });
    },
    //----读取
    clearReadSubmitConfig(){
      this.readLoading = false;
      clearInterval(this.readTimer);
    },

    checkReadSubmitConfig(){
      let that = this;
      this.checkProcess(604, this.clearReadSubmitConfig, function(){
        that.getDetail();
      });
    },

    readGEO() {
      let workerDetailParams = {
        recordId: this.vehicleData.recordId,
        sceneDictate: 604
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailParams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitReadSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitReadSubmit() {
      this.loading = true;
      let updateDataRecord = {
        recordId: this.vehicleData.recordId,
        templateCode: 'vehicle',
        updateData: JSON.stringify({}),
        dictate : 604, //读取GTSPD
        sceneDictate : 604
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.readLoading = true; //转圈
          this.readTimer = setInterval(this.checkReadSubmitConfig, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    updateEditVisible(value) {
      this.$emit('update:editVisible', value);
    },

  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
